import numpy as np
from random import shuffle

def softmax_loss_naive(W, X, y, reg):

  # Initialize the loss and gradient to zero.
  loss = 0.0
  dW = np.zeros_like(W)

  num_classes = W.shape[1]
  num_train = X.shape[0]
  for i in range(num_train):
      scores = X[i].dot(W)
      correct_class = y[i]
      exp_scores = np.zeros_like(scores)
      row_sum = 0
      for j in range(num_classes):
          exp_scores[j] = np.exp(scores[j])
          row_sum += exp_scores[j]
      loss += -np.log(exp_scores[correct_class]/row_sum)
      #compute dW loops:
      for k in range(num_classes):
        if k != correct_class:
          dW[:,k] += exp_scores[k] / row_sum * X[i]
        else:
          dW[:,k] += (exp_scores[correct_class]/row_sum - 1) * X[i]
  loss /= num_train
  reg_loss = 0.5 * reg * np.sum(W**2)
  loss += reg_loss
  dW /= num_train
  dW += reg * W

  return loss, dW
  '''
def softmax_loss_vectorized(W, X, y, reg):
  """
  Softmax loss function, vectorized version.

  Inputs and outputs are the same as softmax_loss_naive.
  """
  # Initialize the loss and gradient to zero.
  loss = 0.0
  dW = np.zeros_like(W)
  num_train=X.shape[0]
  #############################################################################
  # TODO: Compute the softmax loss and its gradient using no explicit loops.  #
  # Store the loss in loss and the gradient in dW. If you are not careful     #
  # here, it is easy to run into numeric instability. Don't forget the        #
  # regularization!                                                           #
  #############################################################################
  scores=X.dot(W)
  correct_class_score  =scores[np.arrange(num_train),y].reshape(num_train,1)
  exp_sum=np.sum(np.exp(scores),axis=1).reshape(num_train,1)
  loss += np.sum(np.log(exp_sum)-correct_class_score)
  
  margin=np.exp(scores)/exp_sum
  margin[np.arrange(num_train),y]+=-1
  dW=X.T.dot(margin)
  
  loss/=num_train
  dW /= num_train
  loss += 0.5*reg*np.sum(W*W)
  dW+=reg*W
  #############################################################################
  #                          END OF YOUR CODE                                 #
  #############################################################################

  return loss, dW

'''
'''
def softmax_loss_vectorized(W, X, y, reg):
  """
  Softmax loss function, vectorized version.

  Inputs and outputs are the same as softmax_loss_naive.
  """
  # Initialize the loss and gradient to zero.
  loss = 0.0
  dW = np.zeros_like(W)
  scores = X.dot(W) 
  scores = np.exp(scores) 
  scores = normalized(scores)
  num_classes = W.shape[1]
  num_train = X.shape[0]

  margins = -np.log(scores)
  ve_sum = np.sum(margins,axis=1)/num_classes
  y_trueClass = np.zeros_like(margins)
  y_trueClass[range(num_train), y] = 1.0
  loss += (np.sum(ve_sum) / num_train)
  dW += np.dot(X.T,scores-y_trueClass)/num_train

  return loss, dW

def normalized(a):
    sum_scores =  np.sum(a,axis=1)
    sum_scores =  1 / sum_scores
    result = a.T * sum_scores.T
    return result.T
'''

'''
def softmax_loss_vectorized(W, X, y, reg):
  """
  Softmax loss function, vectorized version.

  Inputs and outputs are the same as softmax_loss_naive.
  """
  # Initialize the loss and gradient to zero.
  loss = 0.0
  dW = np.zeros_like(W)
  num_train=X.shape[0]
  #############################################################################
  # TODO: Compute the softmax loss and its gradient using no explicit loops.  #
  # Store the loss in loss and the gradient in dW. If you are not careful     #
  # here, it is easy to run into numeric instability. Don't forget the        #
  # regularization!                                                           #
 
# *****START OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****
    num_train = X.shape[0]

    score = X.dot(W)
    # axis = 1每一行的最大值，score仍为500*10
    score -= np.max(score,axis=1)[:,np.newaxis]
    # correct_score变为500 * 1
    correct_score = score[range(num_train), y]
    exp_score = np.exp(score)
    # sum_exp_score维度为500*1
    sum_exp_score = np.sum(exp_score,axis=1)
    # 计算loss
    loss = np.sum(np.log(sum_exp_score) - correct_score)
    loss /= num_train
    loss += 0.5 * reg * np.sum(W * W)

    # 计算梯度
    margin = np.exp(score) / sum_exp_score.reshape(num_train,1)
    margin[np.arange(num_train), y] += -1
    dW = X.T.dot(margin)
    dW /= num_train
    dW += reg * W

    # *****END OF YOUR CODE (DO NOT DELETE/MODIFY THIS LINE)*****

  return loss, dW
'''
def softmax_loss_vectorized(W, X, y, reg):

  # Initialize the loss and gradient to zero.
  loss = 0.0
  dW = np.zeros_like(W)

  num_train = X.shape[0]
  scores = X.dot(W)
  correct_class_score = scores[np.arange(num_train),y].reshape(num_train,1)
  exp_sum = np.sum(np.exp(scores),axis=1).reshape(num_train,1)
  loss += np.sum(np.log(exp_sum) - correct_class_score)
  loss /= num_train
  loss += 0.5 * reg * np.sum(W * W)

  #compute gradient
  margin = np.exp(scores) / exp_sum
  margin[np.arange(num_train),y] += -1
  dW = X.T.dot(margin)
  dW /= num_train
  dW += reg * W

  return loss, dW